<template>
  <div class="container index-page"
       v-title
       data-title='分销助手'
       :style="{position:(showCode?'fixed':'relative')}">
    <div style="background:#fff;margin-bottom: 10px">
      <div class="header-info"
           v-isShow>
        <div class="headerImg">
          <img src="../../assets/images/photo.svg">
        </div>
        <p class="user-name">{{member.accountName}}</p>
        <p class="user-job">分销人员</p>
      </div>
    </div>
    <div class="entry-list"
         v-isShow>
      <div class="col-sm-12 recommend-number">
        <div class="template-row-list">
          <label class="label-title">推荐客户: </label>
          <div class="row-content num"><strong>&nbsp;&nbsp;{{customer.reportCount}}</strong>位</div>
        </div>
      </div>
      <div class="col-sm-12 recommend-number">
        <div class="template-row-list">
          <label class="label-title">佣金总额: </label>
          <div class="row-content num"><strong>&nbsp;&nbsp;{{customer.commissionAmount}}</strong>元</div>
        </div>
      </div>
    </div>
    <div class="recommend-commission-btn"
         v-isShow>
      <div class="col-sm-4">
        <div class="recommend-com-list"
             @click="addCustomer">
          <div class="iconImg"></div>
          <div class="icon-title">我要推荐</div>
        </div>
      </div>
      <div class="col-sm-4"
           @click="myCommission">
        <div class="recommend-com-list botNo">
          <div class="iconImgTwo"></div>
          <div class="icon-title">我的佣金</div>
        </div>
      </div>
      <div class="col-sm-4"
           @click="showQrcode">
        <div class="recommend-com-list botNo">
          <div class="icon-qrcode"><i class="icon-qrcode-i fa fa-qrcode"
               aria-hidden="true"></i></div>
          <div class="icon-title">邀请注册</div>
        </div>
      </div>
    </div>

    <div class="col-sm-12 area-location"
         id="location">
      <!--搜索框  start-->
      <div class="col-sm-12"
           v-show="isSearch">
        <div class="mint-searchbar"
             style="padding: 0 10px;">
          <div class="mint-searchbar-inner">
            <i class="mintui mintui-search"></i>
            <input type="search"
                   v-model="params.name"
                   placeholder="请输入楼盘名称"
                   class="mint-searchbar-core"
                   style="margin-left: 8px;">
            <i id="closeIcon"
               class="mintui mintui-field-error"
               style="color: #8f8e94;display: none;"
               @click="searchList('init')"></i>
          </div>
          <a @click="searchList"
             class="mint-searchbar-cancel"
             style="color: #fe5419;font-weight: bold;font-size: 14px;">搜索</a>
          <a @click="cancelSearch"
             class="mint-searchbar-cancel"
             style="color: #fe5419;font-weight: bold;font-size: 14px;">取消</a>
        </div>
      </div>
      <!--搜索框  end-->
      <!-- 区域定位 -->
      <div v-show="!isSearch">
        <div class="col-sm-8 bor-r">
          <div><i class="position-icon fa fa-map-marker"
               aria-hidden="true"
               @click='getCurrentLocation'></i>
            <a @click="areaSelectShow = !areaSelectShow"><span style="display: inline-block;width: 160px;">{{provinceName}}{{cityName}}{{areaName}}</span></a>
          </div>
          <!-- 区域选择 start -->
          <div class="area-select"
               v-show="areaSelectShow">
            <div class="area-select-sub borer-right">
              <ul>
                <li v-for="(item, index) in cityList"
                    @click="getAreaByCity(item,true);citySelectIndex=index"
                    :class="citySelectIndex==index?'color-orange':''">{{item.cityName}}(<span>{{item.premisesCount}}</span>)</li>
              </ul>
            </div>
            <div class="area-select-sub border-left">
              <i class="fold fa fa-times"
                 @click="areaSelectShow=false"></i>
              <ul>
                <li v-for="(item, index) in areaList"
                    @click="getPremisesWithArea(item)">{{item.areaName}}(<span>{{item.premisesCount}}</span>)</li>
              </ul>
            </div>
          </div>
          <!-- 区域选择 end -->
        </div>
        <div class="col-sm-3 bor-r text-center"><button class="location-btn"
                  @click="showSelect">筛选</button></div>
        <div class="col-sm-1 text-center"><button class="location-btn"
                  @click="showSearch"><i class="fa fa-search"
               aria-hidden="true"></i></button></div>
      </div>
      <!-- 区域定位 end-->
    </div>
    <div class="unified-template"
         id='unified-template'
         style="margin-top:5px;">
      <!-- <div class="choice-city-region">
				<router-link class="choice-city" to="/cityList">
					<span class="location-icon"></span>
					<p class="city-name">{{cityName}}</p>
					<i class="fa fa-caret-right"></i>
				</router-link>
			</div> -->
      <div class="apollo-filter-bar"
           v-show="false">
        <div class="apollo-filter-bar-item"
             :class="{'apollo-filter-bar-item-active': selectAreaBar}"
             @click="selectArea">
          <span class="apollo-filter-bar-item-text">区域范围</span>
          <div class="apollo-filter-bar-triangle"></div>
        </div>
        <div class="apollo-filter-bar-item"
             :class="{'apollo-filter-bar-item-active': selectPriceBar}"
             @click="selectPrice">
          <span class="apollo-filter-bar-item-text">均价范围</span>
          <div class="apollo-filter-bar-triangle"></div>
        </div>
        <div class="apollo-filter-bar-item"
             :class="{'apollo-filter-bar-item-active': selectPropertyBar}"
             @click="selectProperty">
          <span class="apollo-filter-bar-item-text">物业类型</span>
          <div class="apollo-filter-bar-triangle"></div>
        </div>
      </div>
      <div v-show="selectAreaBar">
        <div class="apollo-mobile-modal-mask"
             style="margin-top: 240px;"
             @click="closeMark"></div>
        <div class="apollo-mobile-modal-wrap apollo-mobile-modal-wrap-popup"
             role="dialog"
             v-login>
          <div role="document"
               class="apollo-mobile-modal apollo-mobile-modal-popup apollo-mobile-modal-popup-slide-down"
               style="">
            <div class="apollo-mobile-modal-content">
              <div class="apollo-mobile-modal-body"
                   style="max-height: 215px;">
                <div class="apollo-cascading-menu">
                  <div class="apollo-mobile-list"
                       style="border-right: 1px solid #d5d5d5">
                    <div class="apollo-mobile-list-body"
                         v-for="(item, index) in cityList"
                         :key="index"
                         @click="checkedCity(item, index)">
                      <div class="apollo-mobile-list-item apollo-mobile-list-item-middle"
                           style=""
                           :class="{'apollo-cascading-menu-item-checked': index === activeIndex}">
                        <div class="apollo-mobile-list-line">
                          <div class="apollo-mobile-list-content">{{item.cityName}}</div>
                        </div>
                        <div class="apollo-mobile-list-ripple"
                             style="display: none;"></div>
                      </div>
                    </div>
                  </div>
                  <div class="apollo-mobile-list">
                    <div class="apollo-mobile-list-body"
                         v-for="(item, index) in areaList"
                         :key="index"
                         @click="checkedArea(item, index)">
                      <div class="apollo-mobile-list-item apollo-mobile-list-item-middle"
                           :class="{'apollo-cascading-menu-item-checked': index === areaCheckIndex}">
                        <div class="apollo-mobile-list-line">
                          <div class="apollo-mobile-list-content">{{item.name}}</div>
                        </div>
                        <div class="apollo-mobile-list-ripple"
                             style="display: none;"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-show="selectPriceBar">
        <div class="apollo-mobile-modal-mask"
             style="margin-top: 240px;"
             @click="closeMark"></div>
        <div class="apollo-mobile-modal-wrap apollo-mobile-modal-wrap-popup"
             role="dialog"
             v-login>
          <div role="document"
               class="apollo-mobile-modal apollo-mobile-modal-popup apollo-mobile-modal-popup-slide-down"
               style="">
            <div class="apollo-mobile-modal-content">
              <div class="apollo-mobile-modal-body"
                   style="max-height: 215px;">
                <div class="apollo-mobile-list">
                  <div class="apollo-mobile-list-body">
                    <div class="apollo-mobile-list-item apollo-mobile-checkbox-item apollo-mobile-list-item-middle"
                         :class="{'apollo-mobile-checkbox-item-checked': index === priceActiveindex}"
                         @click="checkedSel(index)"
                         v-for="(item, index) in priceList"
                         :key="index">
                      <div class="apollo-mobile-list-line"
                           @click="checkedPrice(item)">
                        <div class="apollo-mobile-list-content">{{item.label}}</div>
                        <div class="apollo-mobile-list-extra">
                          <label class="apollo-mobile-checkbox-wrapper">
                            <span class="apollo-mobile-checkbox"
                                  :class="{'apollo-mobile-checkbox-checked': index === priceActiveindex }">
                              <input type="checkbox"
                                     class="apollo-mobile-checkbox-input"
                                     value="on">
                              <span class="apollo-mobile-checkbox-inner"></span>
                            </span>
                          </label>
                        </div>
                      </div>
                      <div class="apollo-mobile-list-ripple"
                           style="display: none;"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-show="selectPropertyBar">
        <div class="apollo-mobile-modal-mask"
             style="margin-top: 240px;"
             @click="closeMark"></div>
        <div class="apollo-mobile-modal-wrap apollo-mobile-modal-wrap-popup"
             role="dialog"
             v-login>
          <div role="document"
               class="apollo-mobile-modal apollo-mobile-modal-popup apollo-mobile-modal-popup-slide-down"
               style="">
            <div class="apollo-mobile-modal-content">
              <div class="apollo-mobile-modal-body"
                   style="max-height: 215px;">
                <div class="apollo-mobile-list">
                  <div class="apollo-mobile-list-body">
                    <div class="apollo-mobile-list-item apollo-mobile-checkbox-item apollo-mobile-list-item-middle"
                         :class="{'apollo-mobile-checkbox-item-checked': index === propertyActiveIndex}"
                         @click="checkedPropertySel(index)"
                         v-for="(item, index) in propertyList"
                         :key="index">
                      <div class="apollo-mobile-list-line"
                           @click="checkedEstateType(item)">
                        <div class="apollo-mobile-list-content">{{item.label}}</div>
                        <div class="apollo-mobile-list-extra">
                          <label class="apollo-mobile-checkbox-wrapper">
                            <span class="apollo-mobile-checkbox"
                                  :class="{'apollo-mobile-checkbox-checked': index === propertyActiveIndex }">
                              <input type="checkbox"
                                     class="apollo-mobile-checkbox-input"
                                     value="on">
                              <span class="apollo-mobile-checkbox-inner"></span>
                            </span>
                          </label>
                        </div>
                      </div>
                      <div class="apollo-mobile-list-ripple"
                           style="display: none;"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <ul class="city-info-list"
          v-if="premisesCount !=0">
        <li v-for="(item, index) in premisesList"
            :key="index">
          <div class="residential-details">
            <div class="residential-img"
                 @click="toPremisesDetail(item.id)">

              <img v-if="item.panoramicView"
                   class="panorama360"
                   src="./../../assets/images/panorama360.png">
              <span class="residential-icon"
                    v-if="!(item.reward==0 || item.reward == '' || item.reward == null)"
                    v-isShow>带看有奖</span>
              <span class="subscript"
                    v-if="item.mainPush==2">主推</span>
              <img :src="item.url">
              <div class="residential-mask"></div>
              <div class="residential-mask-info">
                <div class="col-sm-6 name">[ {{item.area.name}} ] {{item.name}}</div>
                <div class="col-sm-6 square">{{item.averagePrice}}&nbsp;元/平米</div>
              </div>
            </div>

            <div class="recommend-residential"
                 v-isShow>
              <div class="userNum">
                已推荐<span class="text"
                      style="padding-left: 14px;">
                  {{item.reportCount == null?0:item.reportCount}}位</span>
              </div>
              <div class="userNum">所在区域<span class="text">{{item.area.name}}</span></div>
              <div class="userNum">渠道经理<span class="tNum"
                      style="text-decoration: underline"
                      @click="callPhone(item.mobile)">{{item.manager}}</span></div>
              <div class="recommendBtn">
                <a href="javascript:;"
                   class="commission-btn"
                   @click="commissionInfoShow(item)">
                  {{item.commissionTitle}}
                </a>
                <a href="javascript:;"
                   class="recommendBtnOne"
                   @click="toRecCustomer(item.id)">
                  推荐客户
                </a>
                <a v-if="item.marketingNumber"
                   href="javascript:;"
                   class="recommendBtnTwo"
                   style="margin-left:20px"
                   @click="callPhone(item.marketingNumber)">
                  联系案场
                </a>
                <template v-else>
                  <a v-if="item.caseMemberPhone"
                     href="javascript:;"
                     class="recommendBtnTwo"
                     style="margin-left:20px"
                     @click="callPhone(item.caseMemberPhone)">
                    联系案场
                  </a>
                </template>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <mugen-scroll :handler="getPremisesList"
                    :should-handle="!loading">
      </mugen-scroll>
    </div>
    <div class="result-warning"
         v-if="premisesCount ==0">
      <i class="fa fa-exclamation-triangle"
         aria-hidden="true"></i>
      {{warningInfo}}
    </div>
    <Qrcode v-bind:qrcode="qrcodeNode"
            :showCode.sync="showCode"
            ref="qrCode"></Qrcode>
    <Select ref="select"
            v-show="choice"
            v-on:getPremises="getPremisesWithPriceAndProperty"></Select>
    <mt-popup style="border-radius: 10px;"
              v-model="addCustomerVisible">
      <div style=""
           class="add-customer"
           style="width: 200px;">
        <span class="item item-border"
              style="padding-bottom: 18px;"
              @click="goRoute('/addCustomer')"><i class="report-one" />立即报备</span>
        <!-- <span class="item" @click="goRoute('/addCustomerForMany')"><i class="report-more" />一客多盘</span> 一客一盘-->
      </div>
    </mt-popup>
    <mt-popup v-model="commissionInfoVisible"
              style="width: 300px; padding: 15px; border-radius: 5px;"
              popup-transition="popup-fade">
      <div>
        <p>{{commissionInfo.name}}的分销佣金</p>
        <div style="font-size: 14px;
    font-weight: 600;
    border-bottom: 1px solid #ccc;
    margin: 7px 0;
    padding-bottom: 8px;">
          <span>方案名称</span>
          <span style="float: right"> 佣金</span>
        </div>
        <div>
          <ul>
            <li v-for="item in commissionInfo.list"
                style="padding: 5px 0;">
              <span class="">{{item.name}}</span>
              <i style="    width: 66%; margin-left: 11px;
    display: inline-block;
    border: 0.5px dashed #ccc;
    position: relative;
    top: -4px;
    text-align: center;"></i>
              <span class=""
                    style="float: right; color: #ff7900">{{item.typeValue + item.type}}</span>
            </li>
          </ul>
        </div>
      </div>
    </mt-popup>
  </div>
</template>
<style>
@import url("../../assets/css/homeBar.css");
.icon-title {
  height: 30px;
  line-height: 30px;
}
.icon-qrcode {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background: #fbfae5;
  background-position: center;
  background-size: 70%;
  margin: 0 auto;
}
.icon-qrcode-i {
  font-size: 30px;
  line-height: 50px;
  color: #fed235;
}
.area-location {
  background: #fff;
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  width: 100%;
  z-index: 50;
  position: relative;
}
.area-location a span {
  font-size: 16px;
}
.position-icon {
  color: #908f8f;
  width: 40px;
  text-align: center;
  font-size: 20px;
  line-height: 50px;
}
.location-btn {
  background: none;
  border: none;
  font-size: 16px;
}
.text-center {
  text-align: center;
}
.fix {
  position: fixed;
  top: 0;
  left: 0;
  margin-bottom: 1px;
  border-bottom: 1px solid #ccc;
  box-shadow: 0 0 1px #000 inset;
}
.area-select {
  width: 100%;
  max-height: 240px;
  position: absolute;
  top: 62px;
  left: 0;
  background: #fff;
  border-bottom: 1px solid #cccccc;
}
.area-select-sub {
  width: 50%;
  float: left;
  max-height: 240px;
  overflow: scroll;
}
.border-right {
  border-right: 1px solid #ccc;
}
.border-left {
  border-left: 1px solid #ccc;
}
.area-select li {
  font-size: 14px;
  padding-left: 15px;
  line-height: 40px;
  height: 40px;
}
.area-select li span {
  color: #fe9229;
}
.color-orange {
  color: #fe9229;
}
.result-warning {
  background: none;
  text-align: center;
  height: 60px;
  margin-top: 100px;
  font-size: 24px;
}
.fold {
  position: absolute;
  right: 5px;
  top: 5px;
}
.residential-img .panorama360 {
  position: absolute;
  width: 80px !important;
  height: 40px !important;
  left: 0;
}
.add-customer {
  padding: 20px;
  text-align: center;
}
.add-customer .item.item-border {
  border-bottom: 1px solid #ccc;
}
.add-customer .item {
  padding: 10px 0;
  font-size: 16px;
  display: inline-block;
  width: 100%;
}
.add-customer .report-one,
.add-customer .report-more {
  display: inline-block;
  width: 30px;
  height: 30px;
  position: relative;
  top: 8px;
  margin-right: 15px;
  background-repeat: no-repeat;
}
.report-one {
  background-image: url("../../assets/images/report-one.png");
}
.report-more {
  background-image: url("../../assets/images/report-more.png");
}
</style>

<script>
import MugenScroll from "vue-mugen-scroll";
import Qrcode from "../common/QRCode.vue";
import Select from "../common/select.vue";
import { MessageBox } from "mint-ui";
import reportFailDialogOptions from "../../js/reportFailDialogOptions";
import Utils from "../../js/utils";
export default {
  data() {
    return {
      commissionInfo: {
        name: "保利",
        list: [
          // {
          // 	name: '别墅',
          // 	typeValue: '10000',
          // 	type: '元'
          // }
        ]
      },
      commissionInfoVisible: false, // 佣金弹框
      addCustomerVisible: false, // 我要推荐 弹框
      params: {
        pageSize: 15,
        pageNo: 0,
        cityId: "",
        areaId: "",
        name: "" //楼盘名称
      },
      isSearch: false,
      cityName: "全部城市",
      customer: {
        totalAmount: 0,
        reportCount: 0,
        commissionAmount: 0.0
      },
      member: {
        accountName: window.localStorage.getItem("3_userName"),
        accountId: window.localStorage.getItem("3_userId")
      },
      premisesList: [],
      loading: false,
      selectPriceBar: false,
      selectAreaBar: false,
      selectPropertyBar: false,
      checkedPriceItem: false,
      propertyList: [{ label: "不限", value: "" }],
      priceList: [
        { label: "不限", value: "" },
        { label: "1万以下", value: "<=10000" },
        { label: "1-2万", value: "10000-20000" },
        { label: "2-3万", value: "20000-30000" },
        { label: "3-4万", value: "30000-40000" },
        { label: "4-5万", value: "40000-50000" },
        { label: "5-8万", value: "50000-80000" },
        { label: "8-10万", value: "80000-100000" },
        { label: "10-15万", value: "100000-150000" },
        { label: "15万以上", value: ">150000" }
      ],
      cityList: [],
      areaList: [],
      activeIndex: -1,
      priceActiveindex: -1,
      propertyActiveIndex: -1,
      areaCheckIndex: -1,
      distanceHeight: false,
      qrcodeNode: {},
      choice: false,
      areaSelectShow: false,
      point: {},
      provinceName: "",
      cityName: "",
      areaName: "",
      resultAddress: "",
      citySelectIndex: 0,
      areaSelectIndex: -1,
      premisesCount: null,
      //lastPremisesCityId:'',
      //lastPremisesAreaId:'',
      totalPages: "",
      warningInfo: "当前定位没有楼盘",
      showCode: false
    };
  },
  components: {
    MugenScroll,
    Qrcode,
    Select,
    MessageBox
  },
  mounted: function () {
    this.sendOpenId();
    this.wxConfig();
    // this.initWeixin();
    // this.goToLocation();
    this.initEstateTypeEnums();
    this.initPremisesCityList();
    this.getPartnerInfo();
    this.initCustomerInfo();
    $("#goble_menu_div").show();
    // this.showTips();
    if (this.$route.params.cityName) {
      this.cityName = this.$route.params.cityName;
    }
    this.bodyInit();
  },
  watch: {
    "params.name": function (newVal) {
      if (newVal && newVal != null && newVal != "") {
        $("#closeIcon").show();
      } else {
        $("#closeIcon").hide();
      }
    }
  },
  methods: {
    // 在index页面获取openId给后端，更新数据库的userId对应最新openId,使得发送微信模板消息到正确的手机上
    sendOpenId() {
      let isLogin = window.localStorage.getItem("3_isLogin");
      if (!isLogin) {
        return;
      }
      let openId = window.localStorage.getItem("3_wxOpenid") || "";
      let userId = window.localStorage.getItem("3_userId") || "";
      let url = this.utilHelper.apiUrl + "/weixin/refreshOpenId";
      if (openId && userId) {
        this.$http.post(url, { openId, userId });
      }
    },
    goRoute(path) {
      this.$router.push(path);
    },
    commissionInfoShow(item) {
      this.commissionInfoVisible = true;
      this.commissionInfo.name = item.name;
      this.$set(this.commissionInfo, "list", item.commissionList);
    },
    showSearch: function () {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
      this.isSearch = !this.isSearch;
    },
    callPhone(mobile) {
      if (mobile) {
        window.location.href = "tel:" + mobile;
      } else {
        layer.msg("手机号不存在", {
          time: 2000
        });
      }
    },
    initEstateTypeEnums: function () {
      var _self = this;
      var body = {};
      body.params = {};
      var url = this.utilHelper.apiUrl + "/common/getEnum/EstateTypeEnum";
      _self.$http.get(url, body).then((response) => {
        var body = response.body.data;
        Object.keys(body).forEach(function (key) {
          var estateType = {};
          estateType.label = body[key];
          estateType.value = key;
          _self.propertyList.push(estateType);
        });
      });
    },
    initPremisesCityList: function () {
      var _self = this;
      var body = {};
      body.params = {};
      var url = this.utilHelper.apiUrl + "/api/getPremisesCityGroupList";
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == 1) {
          var premisesCityList = body.resData.premisesCityList;
          if (!premisesCityList || premisesCityList.length == 0) {
            _self.warningInfo = "没有指定分销楼盘";
          }
          //_self.lastPremisesCityId = body.resData.cityId;
          //_self.lastPremisesAreaId= body.resData.areaId;
          if (premisesCityList) {
            var premisesCount = 0;
            var all_city = {
              cityId: null,
              cityName: "全部",
              premisesCount: premisesCount
            };
            _self.cityList.push(all_city);
            for (var ii = 0; ii < premisesCityList.length; ii++) {
              premisesCount += premisesCityList[ii].premisesCount;
              _self.cityList.push(premisesCityList[ii]);
            }
            _self.cityList[0].premisesCount = premisesCount;
            _self.initWeixin();
          }
        } else {
        }
      });
    },
    closeMark: function () {
      this.selectPriceBar = false;
      this.selectAreaBar = false;
      this.selectPropertyBar = false;
    },
    // 取消搜索，重新获取列表
    cancelSearch() {
      this.isSearch = false;
      this.searchList("init");
    },
    searchList: function (flag) {
      var _self = this;
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      if (flag && flag == "init") {
        _self.params.name = "";
        $("#closeIcon").hide();
      }
      //重新加载楼盘信息
      _self.premisesList = [];
      _self.getPremisesList();
    },
    checkedCity: function (item, index) {
      this.activeIndex = index;
      var _self = this;
      var cityId = item.cityId;
      var cityName = item.cityName;
      var _self = this;
      _self.areaList = [{ id: "", name: "不限" }];
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      _self.params.cityId = "";
      _self.params.areaId = "";
      if (cityId) {
        //选择测试查询数据
        _self.params.cityId = cityId;
        var body = {};
        body.params = { areaId: cityId, userId: "-1" };
        var url = this.utilHelper.apiUrl + "/api/getArea";
        _self.$http.post(url, body).then((response) => {
          var body = response.body;
          if (body.result == 1) {
            var areaResList = body.resData.areaList;
            if (areaResList) {
              for (var ii = 0; ii < areaResList.length; ii++) {
                _self.areaList.push(areaResList[ii]);
              }
            }
          } else {
          }
        });
      }
      //重新加载楼盘信息
      _self.premisesList = [];
      _self.getPremisesList();
    },
    checkedArea: function (item, index) {
      this.areaCheckIndex = index;
      this.selectAreaBar = false;
      var _self = this;
      var areaId = item.id;
      var _self = this;
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      _self.params.areaId = "";
      if (areaId) {
        _self.params.areaId = areaId;
      }
      //重新加载楼盘信息
      _self.premisesList = [];
      _self.getPremisesList();
    },
    checkedPrice: function (item) {
      var _self = this;
      var averagePrice = item.value;
      var _self = this;
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      _self.params.averagePrice = "";
      if (averagePrice) {
        _self.params.averagePrice = averagePrice;
      }
      //重新加载楼盘信息
      _self.premisesList = [];
      _self.getPremisesList();
    },
    checkedEstateType: function (item) {
      var _self = this;
      var estateType = item.value;
      var _self = this;
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      _self.params.estateType = "";
      if (estateType) {
        _self.params.estateType = estateType;
      }
      //重新加载楼盘信息
      _self.premisesList = [];
      _self.getPremisesList();
    },
    checkedSel: function (index) {
      this.priceActiveindex = index;
      this.selectPriceBar = false;
    },
    checkedPropertySel: function (index) {
      this.propertyActiveIndex = index;
      this.selectPropertyBar = false;
    },
    colseCitySel: function () {
      this.selectAreaBar = false;
    },
    selectPrice: function () {
      this.selectPriceBar = !this.selectPriceBar;
      this.selectAreaBar = false;
      this.selectPropertyBar = false;
    },
    selectArea: function () {
      this.selectPriceBar = false;
      this.selectAreaBar = !this.selectAreaBar;
      this.selectPropertyBar = false;
    },
    selectProperty: function () {
      this.selectPriceBar = false;
      this.selectAreaBar = false;
      this.selectPropertyBar = !this.selectPropertyBar;
    },
    initCustomerInfo: function () {
      var userId = window.localStorage.getItem("3_isLogin");
      if (!userId) {
        //用户未登录时，直接返回
        return;
      }
      var _self = this;
      var body = {};
      body.params = {};
      var url = this.utilHelper.apiUrl + "/api/getCustomerPremises";
      this.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == 1) {
          this.customer.commissionAmount = _self.changeToDecimal(
            body.resData.commissionAmount,
            2
          );
          this.customer.reportCount = body.resData.reportCount;
        }
      });
    },
    //实时获取用户信息
    getPartnerInfo() {
      var userId = window.localStorage.getItem("3_isLogin");
      if (!userId) {
        //用户未登录时，直接返回
        return;
      }
      var _self = this;
      var body = {};
      body.params = {};
      var url = this.utilHelper.apiUrl + "/api/getUserById";
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        var result = data.result;
        if (result == "1") {
          window.localStorage.setItem("3_userId", data.id);
          window.localStorage.setItem("3_userName", data.accountName);
          window.localStorage.setItem("3_phone", data.phone);
          window.localStorage.setItem("3_isLogin", true);
          window.localStorage.setItem("3_userRole", data.userRoleId);
          window.localStorage.setItem("3_accountType", data.accountType);

          _self.getParentDept(data.deptId, data.higherid);
        }
      });
    },
    getPremisesList: function () {
      var _self = this;
      //去除由组件导致的页面自动加载
      if (_self.cityName == "") {
        return;
      }
      //if(_self.citySelectIndex == -1){
      //    return;
      //}
      var userId = window.localStorage.getItem("3_isLogin");
      _self.params.pageNo = _self.params.pageNo + 1;
      if (_self.params.pageNo > 1 && _self.params.pageNo > _self.totalPages) {
        layer.msg("已经没有更多数据了！");
        return;
      }
      var index = layer.load();
      _self.loading = true;
      var body = {};
      body.params = _self.params;
      var url = _self.utilHelper.apiUrl + "/api/getAgentPremisesPage";
      if (!userId) {
        //用户未登录时，加载开发商的所有楼盘
        url = _self.utilHelper.apiUrl + "/api/getDevPremisesPage";
      }
      _self.$http.post(url, body).then((response) => {
        layer.close(index);
        var body = response.body;
        if (body.result == "1") {
          var rows = body.resData.getAgentPremisesPage.rows;
          var total = body.resData.getAgentPremisesPage.totalPages;
          var current = body.resData.getAgentPremisesPage.pageNumber;
          _self.premisesCount = body.resData.getAgentPremisesPage.total;
          _self.totalPages = total;

          if (_self.params.pageNo > total) {
            _self.loading = true;
          } else {
            _self.loading = false;
          }

          let premisesList = [];
          if (current > 1) {
            premisesList = _self.premisesList;
          }

          if (rows != null && rows.length > 0) {
            for (var i = 0; i < rows.length; i++) {
              rows[i].averagePrice = _self.setAveragePrice(
                rows[i].averagePrice
              );
              //rows[i].url = _self.setPremisesImg(rows[i].url);
              try {
                rows[i].commissionList = JSON.parse(rows[i].commission || "[]");
              } catch (e) {}
              let tempItem = rows[i].commissionList[0]; // 取第一个佣金方案
              let len = rows[i].commissionList.length;
              if (tempItem) {
                tempItem.name = tempItem.name || "";
                tempItem.typeValue = tempItem.typeValue || "";
                tempItem.type = tempItem.type || "";
                rows[i].commissionTitle =
                  tempItem.name +
                  tempItem.typeValue +
                  tempItem.type +
                  ` (共${len}个方案)`;
              }
            }
            premisesList = premisesList.concat(rows);
          }
          _self.premisesList = premisesList;
        }
      });
    },
    // operationHeader:function(){
    // 	var tHeight = $(".choice-city-region").offset().top;
    // 	$(window).scroll(function() {
    // 		var iScrollT = $(window).scrollTop();
    // 		if(iScrollT > tHeight){
    // 			$(".choice-city-region").css("position","fixed");
    // 		}else{
    // 			$(".choice-city-region").css("position","relative");
    // 		}
    // 	});
    // },
    toPremisesDetail(id) {
      this.$router.push({
        path: "/premisesDetail/" + id
      });
    },
    toRecCustomer(id) {
      //若为游客则弹出绑定对话框
      if (!this.tourist()) {
        return;
      }
      this.$router.replace({
        path: "/recommendCustomer/" + id
      });
    },
    changeToDecimal(value, point) {
      var f_x = parseFloat(value);
      if (isNaN(f_x)) {
        value = "0";
      }
      var f_x = Math.round(value * 100) / 100;
      var s_x = f_x.toString();
      var pos_decimal = s_x.indexOf(".");
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += ".";
      }
      while (s_x.length <= pos_decimal + point) {
        s_x += "0";
      }
      return s_x;
    },
    addCustomer() {
      const _this = this;
      //若为游客则弹出绑定对话框
      //if(!this.tourist()){
      if (Utils.tourist(Utils.getUserRole())) {
        reportFailDialogOptions.btn1 = function () {
          layer.close(index);
        };
        reportFailDialogOptions.btn2 = function () {
          _this.$router.push({ path: "/bindCompany" });
          layer.close(index);
          return;
        };
        var index = layer.open(reportFailDialogOptions);
        return;
      }
      this.addCustomerVisible = true;
      // const prefixUrl = `/?companyUuid=${Utils.getQueryString('companyUuid')}#`
      // let contentHtml = `<div style="" class="add-customer">
      // 										<a class="item item-border" href="${prefixUrl}/addCustomer" ><i class="report-one" />一客一盘</a>
      // 										<a class="item" href="${prefixUrl}/addCustomerForMany" ><i class="report-more" />一客多盘</a>
      // 									</div>`
      // window.addCustomerIndex = layer.open({
      // 	 type: 1
      // 	,title: false
      // 	,area: '200px;'
      // 	,closeBtn: false
      // 	,id: 'aaa'
      // 	,moveType: 1 //拖拽模式，0或者1
      // 	,content: contentHtml
      // });
    },
    myCommission() {
      //若为游客则弹出绑定对话框
      if (!this.tourist()) {
        return;
      }
      this.$router.push({
        path: "/commission"
      });
    },
    //初次进入要显示提示
    showTips() {
      var _self = this;
      if (
        window.sessionStorage.getItem("3_isRegister") &&
        window.sessionStorage.getItem("3_isRegister") == "true"
      ) {
        window.sessionStorage.removeItem("3_isRegister");
        layer.confirm(
          "您的初始登录密码为：x1234567,请及时设置",
          {
            btn: ["以后再说", "去设置"], //按钮
            shade: false //不显示遮罩
          },
          function () {
            layer.closeAll();
          },
          function () {
            _self.$router.push({
              path: "/changepwd"
            });
          }
        );
      }
    },
    //设置均价
    setAveragePrice(averagePrice) {
      if (averagePrice) {
        let price = averagePrice.split(",");
        if (price.length > 1) {
          if (price[0] && price[1]) {
            averagePrice = price[0] + " 至 " + price[1];
          } else if (price[0]) {
            averagePrice = price[0];
          } else if (price[1]) {
            averagePrice = price[1];
          }
        }
      }
      return averagePrice;
    },
    //设置列表图片
    setPremisesImg(imgUrl) {
      if (imgUrl) {
        var index = imgUrl.lastIndexOf(".");
        return (
          imgUrl.substring(0, index) +
          "-m" +
          imgUrl.substring(index, imgUrl.length)
        );
      } else {
        return "";
      }
    },
    getParentDept(deptId, merchantId) {
      var _self = this;
      var body = {};
      body.params = {
        deptId: deptId,
        merchantId: merchantId
      };
      var url = this.utilHelper.apiUrl + "/api/getParentDept";
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        var resData = body.resData;
        _self.qrcodeNode.orgId = resData.orgID;
        _self.qrcodeNode.orgName = resData.orgName;
        if (resData.storeId) {
          _self.qrcodeNode.storeId = resData.storeId;
          _self.qrcodeNode.storeName = resData.storeName;
        } else {
          _self.qrcodeNode.storeId = "";
          _self.qrcodeNode.storeName = "";
        }
        if (resData.groupId) {
          _self.qrcodeNode.groupId = resData.groupId;
          _self.qrcodeNode.groupName = resData.groupName;
        } else {
          _self.qrcodeNode.groupId = "";
          _self.qrcodeNode.groupName = "";
        }
      });
    },
    showQrcode() {
      this.$refs.qrCode.useqrcode();
      this.showCode = true;
      $("#qrCode").show();
    },
    showSelect() {
      $("#choiceModel").show();
    },
    bodyInit() {
      var tit = document.getElementById("location");
      //alert(tit);
      //占位符的位置
      var rect = tit.getBoundingClientRect(); //获得页面中导航条相对于浏览器视窗的位置
      // var inser = document.createElement("div");
      // tit.parentNode.replaceChild(inser,tit);
      // inser.appendChild(tit);
      // inser.style.height = rect.height + "px";
      //获取距离页面顶端的距离
      var titleTop = tit.offsetTop;
      //滚动事件
      document.onscroll = function () {
        //获取当前滚动的距离
        var btop =
          document.body.scrollTop || document.documentElement.scrollTop;
        //如果滚动距离大于导航条据顶部的距离
        if (btop > titleTop) {
          //为导航条设置fix
          tit.className = "col-sm-12 area-location fix";
        } else {
          //移除fixed
          tit.className = "col-sm-12 area-location";
        }
      };
    },
    getPremisesWithPriceAndProperty(params) {
      var _self = this;
      var averagePrice = params.price;
      var estateType = params.property;
      var _self = this;
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      _self.params.averagePrice = "";
      _self.params.estateType = "";
      if (averagePrice) {
        _self.params.averagePrice = averagePrice;
      }
      if (estateType) {
        _self.params.estateType = estateType;
      }

      //重新加载楼盘信息
      _self.premisesList = [];
      _self.getPremisesList();
      $("#choiceModel").hide();
    },
    getAreaByCity(city, isClick) {
      if (isClick === true) {
        window.localStorage.setItem("gpsCityName", city.cityName);
      }
      var _self = this;
      if (city.cityId == null) {
        _self.areaSelectShow = false;
        window.localStorage.setItem("gpsAreaName", null);
      }
      var body = {};
      body.params = {
        cityId: city.cityId
      };
      var url = this.utilHelper.apiUrl + "/api/getAreaAndPremisesCount";
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        var resData = body.resData;
        _self.areaList = resData.premisesAreaList;

        _self.params.cityId = city.cityId;
        _self.params.areaId = "";
        _self.cityName = city.cityName;
        _self.areaName = "";
        _self.provinceName = "";
        // window.localStorage.setItem('gpsCityName',_self.cityName)
        //匹配区域
        if (city.areaName) {
          for (var i in resData.premisesAreaList) {
            if (
              resData.premisesAreaList[i].areaName.search(city.areaName) == 0
            ) {
              _self.areaId = resData.premisesAreaList[i].areaId;
              _self.params.areaId = _self.areaId;
              _self.areaName = city.areaName;
            }
          }
        }

        _self.params.pageNo = 0;
        _self.params.pageSize = 15;
        _self.premisesList = [];
        if (isClick) {
          _self.params.areaId = "";
          _self.areaName = "";
        }
        _self.getPremisesList();
      });
    },
    getPremisesWithArea(area) {
      var _self = this;
      _self.params.pageNo = 0;
      _self.params.pageSize = 15;
      _self.params.areaId = area.areaId;
      _self.areaName = area.areaName;
      _self.premisesList = [];
      _self.areaSelectShow = false;
      window.localStorage.setItem("gpsAreaName", _self.areaName);
      _self.getPremisesList();
    },
    ///////定位/////////////////
    wxConfig() {
      //微信配置
      var _self = this;
      var currUrl = location.href.split("#")[0];
      var body = {};
      body.params = {
        url: currUrl
      };
      var url = this.utilHelper.apiUrl + "/api/js_ticket";
      this.$http.post(url, body).then(
        (response) => {
          var data = response.body.resData;
          wx.config({
            debug: false,
            appId: data.appid, // 必填，公众号的唯一标识
            timestamp: data.time, // 必填，生成签名的时间戳
            nonceStr: data.noncestr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名，见附录1
            jsApiList: ["getLocation"]
          });
        },
        (res) => {
          //_self.cityName = '全部';
          //_self.adaptAddress(_self.cityName, _self.areaName);
        }
      );
    },
    //解析地址
    getAddress(point) {
      var _self = this;
      var geoc = new BMap.Geocoder();
      geoc.getLocation(point, function (rs) {
        var addComp = rs.addressComponents;
        _self.provinceName = addComp.province;
        _self.cityName = addComp.city;
        // _self.resultAddress = addComp.province + addComp.city +  addComp.district + addComp.street  + addComp.streetNumber
        _self.resultAddress =
          addComp.province +
          addComp.city +
          addComp.district +
          addComp.street +
          addComp.streetNumber;
        _self.areaName = addComp.district;
        _self.adaptAddress(_self.cityName, _self.areaName);
      });
      //微信地址解析
    },
    // 获取当前位置
    getCurrentLocation() {
      var _self = this;
      wx.getLocation({
        success: function (res) {
          var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          var url =
            _self.utilHelper.apiUrl +
            "/weixin/getAddress?lat=" +
            latitude +
            "&lng=" +
            longitude;
          _self.$http.get(url).then((response) => {
            var data = response.body;
            if (data.status == 0) {
              let city =
                data.result.ad_info.city == null
                  ? "全部"
                  : data.result.ad_info.city;
              let district =
                data.result.ad_info.district == null
                  ? ""
                  : data.result.ad_info.district;
              window.localStorage.setItem("gpsCityName", city ? city : "全部");
              window.localStorage.setItem(
                "gpsAreaName",
                district ? district : ""
              );
              _self.cityName = city;
              _self.adaptAddress(city, district);
            }
          });
        },
        cancel: function (res) {
          //_self.cityName = '全部';
          ///_self.adaptAddress();
        },
        fail: function (res) {
          //_self.cityName = '全部';
          //_self.adaptAddress();
        }
      });
    },
    goToLocation() {
      var _self = this;
      let cityName = window.localStorage.getItem("gpsCityName");
      let areaName = window.localStorage.getItem("gpsAreaName");
      if (cityName === null) {
        wx.getLocation({
          success: function (res) {
            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            var url =
              _self.utilHelper.apiUrl +
              "/weixin/getAddress?lat=" +
              latitude +
              "&lng=" +
              longitude;
            _self.$http.get(url).then((response) => {
              var data = response.body;
              if (data.status == 0) {
                let city =
                  data.result.ad_info.city == null
                    ? ""
                    : data.result.ad_info.city;
                let district =
                  data.result.ad_info.district == null
                    ? ""
                    : data.result.ad_info.district;
                MessageBox.confirm(
                  "系统检测到您当前位置为" +
                    city +
                    district +
                    " 是否使用当前位置？"
                )
                  .then((action) => {
                    window.localStorage.setItem("gpsCityName", city);
                    window.localStorage.setItem("gpsAreaName", district);
                    _self.cityName = city;
                    _self.adaptAddress(city, district);
                  })
                  .catch(() => {
                    //如果尚未加载楼盘信息，则加载全部信息
                    if (_self.cityName == "") {
                      window.localStorage.setItem("gpsCityName", "全部");
                      window.localStorage.setItem("gpsAreaName", "");
                      _self.cityName = "全部";
                      _self.adaptAddress();
                    }
                  });
              }
            });
          },
          cancel: function (res) {
            if (_self.cityName == "") {
              window.localStorage.setItem("gpsCityName", "全部");
              window.localStorage.setItem("gpsAreaName", "");
              _self.cityName = "全部";
              _self.adaptAddress();
            }
          },
          fail: function (res) {
            if (_self.cityName == "") {
              window.localStorage.setItem("gpsCityName", "全部");
              window.localStorage.setItem("gpsAreaName", "");
              _self.cityName = "全部";
              _self.adaptAddress();
            }
          }
        });
      } else {
        _self.cityName = cityName;
        _self.adaptAddress(cityName, areaName);
      }
    },
    //定位当前位置
    setLocation() {
      //调用微信内置定位获取坐标
      var _self = this;
      //调用ip
      var url = this.utilHelper.apiUrl + "/weixin/getAddressByIp";
      this.$http.get(url).then((response) => {
        var data = response.body;
        if (data.status == 0) {
          _self.cityName = data.result.ad_info.city;
          window.localStorage.setItem(
            "gpsCityName",
            data.result.ad_info.city ? data.result.ad_info.city : "全部"
          );
          window.localStorage.setItem(
            "gpsAreaName",
            data.result.ad_info.district ? data.result.ad_info.district : ""
          );
          _self.adaptAddress(
            data.result.ad_info.city,
            data.result.ad_info.district
          );
        }
      });
    },
    initWeixin() {
      var _self = this;
      var isWeixinClient = false;
      //判断客户端是否为微信
      if (/MicroMessenger/.test(window.navigator.userAgent)) {
        isWeixinClient = true;
      }
      let cityName = window.localStorage.getItem("gpsCityName");
      let areaName = window.localStorage.getItem("gpsAreaName");
      //默认加载楼盘信息
      //_self.adaptAddress(cityName,areaName);
      if (isWeixinClient) {
        //if(cityName===undefined){
        wx.ready(function () {
          _self.goToLocation();
        });
        //}
        //wx.error(function(){
        //  _self.cityName = cityName? cityName: '全部';
        //  _self.adaptAddress();
        //})
      } else {
        _self.cityName = cityName;
        _self.adaptAddress(cityName, areaName);
      }
    },
    adaptAddress(locationCity, locationArea) {
      var _self = this;
      var cityName = "";
      var getCityFlag = false;
      //定位之后获取相应楼盘
      for (let i = 0; i < _self.cityList.length; i++) {
        if (
          _self.cityList[i].cityName == locationCity ||
          _self.cityList[i].cityName.search(locationCity) >= 0
        ) {
          _self.citySelectIndex = i;
          getCityFlag = true;
        }
      }
      if (!locationCity && !locationArea) {
        _self.citySelectIndex = 0;
      }
      if (!getCityFlag) {
        _self.citySelectIndex = 0;
      }
      if (_self.citySelectIndex == 0) {
        _self.getAreaByCity(_self.cityList[0]);
      } else {
        //如果区域信息为空则获取城市信息
        if (locationArea) {
          _self.cityList[_self.citySelectIndex].areaName = locationArea;
        }
        _self.getAreaByCity(_self.cityList[_self.citySelectIndex]);
      }
    }
  }
};
</script>
<style lang="less" scoped>
.index-page {
  .commission-btn {
    top: 0;
    bottom: auto;
    background-color: transparent;
    color: #f07b67;
    border: none;
    font-size: 14px;
    font-weight: 600;
    position: absolute;
    right: 0;
    margin: 3px;
  }
}
.user-name {
  position: absolute;
  color: #fff;
}
.user-job {
  font-size: 12px;
  color: #fff;
  position: absolute;
  bottom: 18%;
  text-align: center;
  width: 100%;
}
</style>


